package com.itboye.sunsun.volley;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xml.sax.XMLReader;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsun.MainHomeActivity;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.luntan.TieZiDetailActivity;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.www.aq.StartActivity;
import com.itboye.sunsunhome.www.aq.base.MyApplication;
import com.pobing.uilibs.extend.component.dialog.ImageViewerDialog;

/**
 * 字符串转表情Spanned 表情格式 [:f000}
 * 
 * @author Young
 * 
 */
public class String2Spanned extends TypeAdapter<Spanned> {

	static Pattern pattern;

	static Map<String, Integer> map = new HashMap<>();

	public static ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			Drawable d = null;
			try {
				int id = Integer.parseInt(source);
				d = App.ctx.getResources().getDrawable(id);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			} catch (Exception e) {
				// TODO: handle exception
				InputStream is = null;
				System.out.println(">>>>>>>>>>>+图片 ID" + source);
				try {
					is = (InputStream) new URL(source).getContent();
					d = Drawable.createFromStream(is, "src");
					d.setBounds(0, 0, MainHomeActivity.screenWidth,
							get_Image_heigth(MainHomeActivity.screenWidth, d));
					System.out
							.println("MainHomeActivity.screenWidth"
									+ MainHomeActivity.screenWidth
									+ "---->"
									+ get_Image_heigth(
											MainHomeActivity.screenWidth, d));
					// d.setBounds(0, 0, d.getMinimumWidth(),
					// d.getMinimumHeight());
					is.close();
					return d;
				} catch (Exception e2) {
					return null;
				}
			}
			return d;
		}
	};

	private static Pattern pattern2;

	/**
	 * 
	 * @param screen_width
	 *            屏幕宽度
	 * @param screen_dpi
	 *            屏幕的密度值
	 * @param bitmap
	 *            图片
	 * @return
	 */
	public static int get_Image_heigth(int screen_width, Drawable bitmap) {
		Bitmap bitmap2 = Bitmap.createBitmap(

		bitmap.getMinimumWidth(),

		bitmap.getMinimumHeight(),

		bitmap.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

		: Bitmap.Config.RGB_565);
		// 图片的宽度和高度
		int image_width = bitmap2.getWidth();
		int image_height = bitmap2.getHeight();
		int widget_height = screen_width * image_height / image_width;
		// height_dip = widget_height * (screen_dpi / 160);
		return widget_height;
	}

	public static int dp2px(Context context, int dp) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5f);
	}

	static {
		pattern2 = Pattern.compile("\\{pic\\d{1,10000}?\\}");
		pattern = Pattern.compile("\\[:f\\d{3}\\}");
		map.put("[:f000}", R.drawable.f000);
		map.put("[:f001}", R.drawable.f001);
		map.put("[:f002}", R.drawable.f002);
		map.put("[:f003}", R.drawable.f003);
		map.put("[:f004}", R.drawable.f004);
		map.put("[:f005}", R.drawable.f005);
		map.put("[:f006}", R.drawable.f006);
		map.put("[:f007}", R.drawable.f007);
		map.put("[:f008}", R.drawable.f008);
		map.put("[:f009}", R.drawable.f009);
		map.put("[:f010}", R.drawable.f010);
		map.put("[:f011}", R.drawable.f011);
		map.put("[:f012}", R.drawable.f012);
		map.put("[:f013}", R.drawable.f013);
		map.put("[:f014}", R.drawable.f014);
		map.put("[:f015}", R.drawable.f015);
		map.put("[:f016}", R.drawable.f016);
		map.put("[:f017}", R.drawable.f017);
		map.put("[:f018}", R.drawable.f018);
		map.put("[:f019}", R.drawable.f019);
		map.put("[:f020}", R.drawable.f020);
		map.put("[:f021}", R.drawable.f021);
		map.put("[:f022}", R.drawable.f022);
		map.put("[:f023}", R.drawable.f023);
		map.put("[:f024}", R.drawable.f024);
		map.put("[:f025}", R.drawable.f025);
		map.put("[:f026}", R.drawable.f026);
		map.put("[:f027}", R.drawable.f027);
		map.put("[:f028}", R.drawable.f028);
		map.put("[:f029}", R.drawable.f029);
		map.put("[:f030}", R.drawable.f030);
		map.put("[:f031}", R.drawable.f031);
		map.put("[:f032}", R.drawable.f032);
		map.put("[:f033}", R.drawable.f033);
		map.put("[:f034}", R.drawable.f034);
		map.put("[:f035}", R.drawable.f035);
		map.put("[:f036}", R.drawable.f036);
		map.put("[:f037}", R.drawable.f037);
		map.put("[:f038}", R.drawable.f038);
		map.put("[:f039}", R.drawable.f039);
		map.put("[:f040}", R.drawable.f040);
		map.put("[:f041}", R.drawable.f041);
		map.put("[:f042}", R.drawable.f042);
		map.put("[:f043}", R.drawable.f043);
		map.put("[:f044}", R.drawable.f044);
		map.put("[:f045}", R.drawable.f045);
		map.put("[:f046}", R.drawable.f046);
		map.put("[:f047}", R.drawable.f047);
		map.put("[:f048}", R.drawable.f048);
		map.put("[:f049}", R.drawable.f049);
		map.put("[:f050}", R.drawable.f050);
		map.put("[:f051}", R.drawable.f051);
		map.put("[:f052}", R.drawable.f052);
		map.put("[:f053}", R.drawable.f053);
		map.put("[:f054}", R.drawable.f054);
		map.put("[:f055}", R.drawable.f055);
		map.put("[:f056}", R.drawable.f056);
		map.put("[:f057}", R.drawable.f057);
		map.put("[:f058}", R.drawable.f058);
		map.put("[:f059}", R.drawable.f059);
		map.put("[:f060}", R.drawable.f060);
		map.put("[:f061}", R.drawable.f061);
		map.put("[:f062}", R.drawable.f062);
		map.put("[:f063}", R.drawable.f063);
		map.put("[:f064}", R.drawable.f064);
		map.put("[:f065}", R.drawable.f065);
		map.put("[:f066}", R.drawable.f066);
		map.put("[:f067}", R.drawable.f067);
		map.put("[:f068}", R.drawable.f068);
		map.put("[:f069}", R.drawable.f069);
		map.put("[:f070}", R.drawable.f070);
		map.put("[:f071}", R.drawable.f071);
		map.put("[:f072}", R.drawable.f072);
		map.put("[:f073}", R.drawable.f073);
		map.put("[:f074}", R.drawable.f074);
		map.put("[:f075}", R.drawable.f075);
		map.put("[:f076}", R.drawable.f076);
		map.put("[:f077}", R.drawable.f077);
		map.put("[:f078}", R.drawable.f078);
		map.put("[:f079}", R.drawable.f079);
		map.put("[:f080}", R.drawable.f080);
		map.put("[:f081}", R.drawable.f081);
		map.put("[:f082}", R.drawable.f082);
		map.put("[:f083}", R.drawable.f083);
		map.put("[:f084}", R.drawable.f084);
		map.put("[:f085}", R.drawable.f085);
		map.put("[:f086}", R.drawable.f086);
		map.put("[:f087}", R.drawable.f087);
		map.put("[:f088}", R.drawable.f088);
		map.put("[:f089}", R.drawable.f089);
		map.put("[:f090}", R.drawable.f090);
		map.put("[:f091}", R.drawable.f091);

	}

	@Override
	public Spanned read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			in.nextNull();
			return null;
		}

		String origStr = in.nextString();
		Matcher matcher = pattern.matcher(origStr);
		StringBuilder stringBuilder = new StringBuilder();

		int last = 0;
		while (matcher.find()) {
			int s = matcher.start();
			int e = matcher.end();
			stringBuilder.append(origStr.substring(last, s));

			String group = matcher.group();
			Integer emojId = map.get(group);
			if (emojId == null) {
				stringBuilder.append(group);
			} else {
				stringBuilder.append("<img src='");
				stringBuilder.append(emojId);
				stringBuilder.append("'/>");
			}

			last = e;

		}
		stringBuilder.append(origStr.substring(last, origStr.length()));
		System.out.println("Spanner222" + "" + stringBuilder.toString());
		return Html.fromHtml(
				stringBuilder.toString().replace("\n", "<br>")
						.replace("&lt;/p&gt;", "<br>")
						.replace("&lt;p dir=&quot;ltr&quot;&gt;", "<br>")
						.replace("&lt;", "<").replace("&gt;", ">"),
				imageGetter, null);// ,
									// imageGetter,
									// null);
	}

	@Override
	public void write(JsonWriter arg0, Spanned arg1) throws IOException {

	}

	static TagHandler tagHandler = new TagHandler() {

		@Override
		public void handleTag(boolean opening, String tag, Editable output,
				XMLReader xmlReader) {
			// TODO Auto-generated method stub

		}
	};

	public static Spanned parsed(String content) {
		if (content == null) {
			// in.nextNull();
			return null;
		}

		// String origStr=content.nextString();

		StringBuilder stringBuilder = new StringBuilder();
		// Matcher matcher2 = pattern2.matcher(content);
		// int last2 = 0;
		// while (matcher2.find()) {
		// int s = matcher2.start();
		// int e = matcher2.end();
		// stringBuilder.append(content.substring(last2, s));
		// stringBuilder.append("<img src=" + NetPublicConstant.IMAGE2
		// + content.substring(s + 4, e - 1) + "/>");
		// last2 = e;
		// }
		// stringBuilder.append(content.substring(last2, content.length()));
		Matcher matcher = pattern.matcher(content);
		int last = 0;
		while (matcher.find()) {

			int s = matcher.start();
			int e = matcher.end();
			stringBuilder.append(content.toString().substring(last, s));

			String group = matcher.group();
			Integer emojId = map.get(group);
			if (emojId == null) {
				stringBuilder.append(group);
			} else {
				stringBuilder.append("<img src='");
				stringBuilder.append(emojId);
				stringBuilder.append("'/>");
			}

			last = e;

		}

		stringBuilder.append(content.substring(last, content.length()));
		Matcher matcher2 = pattern2.matcher(stringBuilder);
		int last2 = 0;
		String pirnt = null;
		StringBuffer stringBuffer = new StringBuffer();

		// 图片Id暂存
		ArrayList<String> arrayImgIds = new ArrayList<>();
		while (matcher2.find()) {
			int s = matcher2.start();
			int e = matcher2.end();
			String group = matcher2.group();
			// {pic123} //图片格式
			int idStart = group.length() + 3;
			int idEnd = group.length() - 1;
			String imgId = group.substring(4, idEnd);
			arrayImgIds.add(imgId);
			last2 = e;
		}
		stringBuilder = new StringBuilder(
				matcher2.replaceAll("<br><img src=" + null + "/>"));

		System.out.println("我是匹配出来的img" + arrayImgIds.size());
		String[] string = stringBuilder.toString().split(
				"<img src=" + null + "/>");
		if (string.length > 0) {
			for (int i = 0; i < string.length; i++) {
				try {
					
					stringBuffer.append(string[i] + "<br><img src='"
							+ NetPublicConstant.IMAGE2+arrayImgIds.get(i) + "'/><br>");
				} catch (Exception e) {
					// TODO: handle exception
					stringBuffer.append(string[i]);//图片Id没有了
				}
			}
		}else{
			stringBuffer=new StringBuffer(stringBuilder);
		}
		System.out.println("我最终的img" + stringBuffer);
		Spanned spanned = Html.fromHtml(
				stringBuffer.toString().replace("\n", "<br>")
						.replace("&lt;/p&gt;", "<br>")
						.replace("&lt;p dir=&quot;ltr&quot;&gt;", "<br>")
						.replace("&lt;u&gt;", "").replace("&lt;/u&gt;", "")
						.replace("&lt;/b&gt;", "").replace("&lt;b&gt;", ""),
				imageGetter, tagHandler2);
		System.out.println("Spanner" + spanned);
		return spanned;// ,
		// imageGetter,
		// null);
	}

	static MTagHandler tagHandler2 = new MTagHandler();

	public static class MTagHandler implements TagHandler {
		private int sIndex = 0;
		private int eIndex = 0;

		public void handleTag(boolean opening, String tag, Editable output,
				XMLReader xmlReader) {
			// TODO Auto-generated method stub
			if (tag.toLowerCase(Locale.getDefault()).equals("img")) {
				Pattern pattern2 = Pattern.compile("-?[0-9]+.?[0-9]+");// 正则表达式判断返回的url是表情（int）还是图片(url字符串)
																		// ---->>>表情：int
																		// 图片：String
				// 获取长度
				int len = output.length();
				// 获取图片地址
				ImageSpan[] images = output.getSpans(len - 1, len,
						ImageSpan.class);
				String imgURL = images[0].getSource();
				// 使图片可点击并监听点击事件
				output.setSpan(new ClickableImage(App.ctx, imgURL), len - 1,
						len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
		}

		private class ClickableImage extends ClickableSpan {
			private String url;
			private Context context;

			public ClickableImage(Context context, String url) {
				this.context = context;
				this.url = url;
			}

			@Override
			public void onClick(View widget) { // 进行图片点击之后的处理 } }}
				Pattern pattern2 = Pattern.compile("-?[0-9]+.?[0-9]+");// 正则表达式判断返回的url是表情（int）还是图片(url字符串)
																		// ---->>>表情：int
																		// 图片：String
				if (pattern2.matcher(url).matches()) {
					// ByAlert.alert("表情" + "");
				} else {
					// ByAlert.alert("图片" + "");
					ImageViewerDialog imageViewerDialog = new ImageViewerDialog(
							TieZiDetailActivity.activity);
					String urls[] = new String[] { url };
					imageViewerDialog.setImageUrls(urls);
					imageViewerDialog.show(0);
				}
			}
		}

	}

}
